package cn.lingyangwl.framework.validation.validator;

import cn.lingyangwl.framework.tool.core.StringUtils;
import cn.lingyangwl.framework.validation.StrToDate;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.SimpleDateFormat;

/**
 * @author shenguangyang
 */
public class StrToDateValidator implements ConstraintValidator<StrToDate, String> {
    private StrToDate strToDate;

    @Override
    public void initialize(StrToDate strToDate) {
        this.strToDate = strToDate;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        // 如果 value 为空则不进行格式验证，为空验证可以使用 @NotBlank @NotNull @NotEmpty 等注解来进行控制，职责分离
        if (StringUtils.isEmpty(value)) {
            return true;
        }
        String format = strToDate.format();
        if (value.length() != format.length()) {
            return false;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        try {
            simpleDateFormat.parse(value);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
